// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: wsfuyibing <682805@qq.com>
// Date: 2025-02-08

package paid

import (
	"context"
	"gitee.com/go-libs/log"
	"gitee.com/go-libs/result"
	"gitee.com/go-libs/validator-iris/validator"
	"gitee.com/go-wares/framework-iris/framework/src/logics"
	"github.com/kataras/iris/v12"
	"integration/app/errs"
	"integration/app/lib/conf"
	"integration/app/lib/nod"
	"integration/app/lib/nod/api"
	"integration/app/lib/nod/sell_order"
	"integration/app/logics/shop"
	"integration/app/models"
	"integration/app/services"
)

// Logic
// 支付完成逻辑.
type Logic struct {
	shop.OrderLogic          // 公共逻辑
	request         *Request // 请求入参
}

// New
// 创建实例.
func New() logics.Logical {
	return &Logic{
		request: &Request{},
	}
}

// Before
// 前置校验.
func (o *Logic) Before(_ context.Context, i iris.Context) (err error) {
	err = validator.Json(i, o.request)
	return
}

// Run
// 执行逻辑.
func (o *Logic) Run(ctx context.Context, _ iris.Context) (res result.Result) {
	var (
		agent      *conf.ErpAgent
		entity     *sell_order.Entity
		err        error
		has        bool
		order      *models.Order
		orderCarts []*models.OrderCartInfo
		sent       *api.PostSellOrderResponse
	)

	res = result.New()

	// 1. 校验来源.
	if agent, has = conf.Config.GetAgent(o.request.Database); !has {
		res.WithError(errs.ErrDatabaseKeyNotConfigured)
		return
	}

	// 2. 加载订单.
	if order, _, orderCarts, err = o.getCrmebOrder(ctx, agent); err != nil {
		res.WithError(err)
		return
	}

	// 3. 初始化客户.
	if _, err = o.InitErpCustomer(ctx, agent, order); err != nil {
		res.WithError(err)
		return
	}

	// 4. 构建入参.
	if entity, err = o.buildErpData(ctx, agent, order, orderCarts); err != nil {
		res.WithError(err)
		return
	}

	// 5. 上报数据.
	if sent, err = o.sendToErp(ctx, agent, entity); err != nil {
		res.WithError(err)
		return
	}

	// 6. 返回结果.
	return res.With(sent)
}

// 构建数据.
func (o *Logic) buildErpData(cts context.Context, agent *conf.ErpAgent, order *models.Order, orderCarts []*models.OrderCartInfo) (entity *sell_order.Entity, err error) {
	ctx := log.NewContextForChildInfo(cts, `build erp data: with crmeb order`)
	entity, err = nod.Builder.SellOrder(ctx, agent, order, orderCarts)
	return
}

func (o *Logic) getCrmebOrder(cts context.Context, agent *conf.ErpAgent) (order *models.Order, orderStatus *models.OrderStatus, orderCarts []*models.OrderCartInfo, err error) {
	ctx := log.NewContextForChildInfo(cts, `load crmeb order: data-from="%s", connection-key="%s" read with status message`, o.request.Database, agent.ConnectionKey)
	if order, orderStatus, orderCarts, err = o.LoadCrmebOrder(ctx, agent, o.request.Data); err != nil {
		log.Errorfc(ctx, `crmeb order fail: error="%v"`, err)
	} else {
		log.Infofc(ctx, `crmeb order info: oid="%d", order_id="%s", pay_type="%s", status="%d"`, order.Id, order.OrderId, order.PayType, order.Status)
	}
	return
}

// 发布数据.
func (o *Logic) sendToErp(cts context.Context, agent *conf.ErpAgent, entity *sell_order.Entity) (sent *api.PostSellOrderResponse, err error) {
	var (
		affects int64
		ctx     = log.NewContextForChildInfo(cts, `send data to erp`)
	)
	if sent, err = nod.Api.PostSellOrder(ctx, agent, entity); err == nil {
		if affects, err = services.NewErpSellsService().SetOutIdByOutTradeNo(ctx, sent.OutId, entity.Order.Number); err == nil {
			log.Infofc(ctx, `data sent: out_id="%d", out_trade_no="%s", affects="%d"`, sent.OutId, entity.Order.Number, affects)
		}
	}
	return
}
